
<template>
  <div style="margin-top: 15px; padding: 0 16px">
    <el-tabs type="border-card" style="min-height: 320px; box-shadow: none">
      <el-tab-pane>
        <template #label>
          <span><i class="el-icon-date"></i>整刀组装看板</span>
        </template>
        <table  class="optimized-table">
          <thead>
            <tr>
              
              <th  style="width: 16%;">工单</th>
              <th style="width: 8%;">位置</th>
              <th style="width: 8%;">已写Rfid</th>
              <th style="width: 5%;">刀柄</th>
              <th style="width: 10%;">刀柄类型</th>
              <th  style="width: 5%;">刀名</th>
              <th  style="width: 7%;">R</th>
              <th style="width: 10%;">对刀长度</th>    
              
              <th style="width: 10%;">刀长</th>
              <th style="width: 10%;">刀柄长</th>
              <th style="width: 10%;">中央刀库异常</th>
              <th style="width: 8%;">使能就绪</th>
              <th style="width: 8%;">RFID可写</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in tableData" :key="index">
              
              <td  style="text-align: center;">
                <template v-if="item.isUse=='True'&&item.isWriteRfid=='True'">
                  <el-tooltip :content="faultNo=='True' ? '可写RFID' : '不可写RFID'" placement="top">
                  <div style="color:green;size: 18px; font-weight: bold" class="input-icon el-icon-unlock"></div>
                </el-tooltip>
                </template>
                <template v-else>
                  <el-tooltip :content="faultNo=='True' ? '可写RFID' : '不可写RFID'" placement="top">
                    <div style="color:red;size: 18px; font-weight: bold" class="input-icon el-icon-lock"></div>
      <!-- <i :class="['status-icon', faultNo=='True' ? 'el-icon-add-location text-success' : 'el-icon-delete-location text-danger']"></i> -->
    </el-tooltip>
                  
                </template>              
                {{ item.identifier }}</td>
              <td style="text-align: center;">{{ (item.location==null||item.location==0)?'-':item.location }}</td>
              <td style="text-align: center;">{{ item.rfidCode }}</td>
              <td  style="text-align: center;">{{ item.handle_type }}</td>
              <td  style="text-align: center;">{{ item.holderTypeId }}</td>
              <td  style="text-align: center;">{{ item.tool_name }}</td>
              <td  style="text-align: center;">{{ item.r==null?'-':item.r }}</td>              
              <td  style="text-align: center;">                
                {{ item.reality_pairing_length==null?'-':item.reality_pairing_length }}
                </td>      
              <td style="text-align: center;" >{{ item.reality_knife_length==null?'-':item.reality_knife_length }}</td>
              <td style="text-align: center;">{{ item.HolderL==null?'-':item.HolderL }}</td>
              <td style="text-align: center;">   

    <span :class="['state-indicator', item.isFalut=='False' ? 'ready-state' : 'warning-state']">
      {{ item.isFalut=='False' ? '正常无异常' : '异常' }}
    </span>
              </td>
              <td style="text-align: center;">
                <template v-if="item.isUse=='True'">
                  <span style='color:green'>已就绪</span>
                </template>
                <template v-else>
                  <span style='color:red'>未就绪</span>
                </template>
                
                </td>
              <td style="text-align: center;">
                <template v-if="item.isWriteRfid=='True'">
                  <span style='color:green'>可写</span>
                </template>
                <template v-else>
                  <span style='color:red'>不可写</span>
                </template>
                <el-tooltip :content="item.isWriteRfid=='True' ? '可写' : '不可写'" placement="top">
      <i :class="['status-icon', item.isWriteRfid=='True' ? 'el-icon-success text-success' : 'el-icon-remove text-danger']"></i>
    </el-tooltip>
                </td>
              <td><img style="width: 40px;height: 40px;" ></td>
            </tr>
            <tr  class="footer-info">
              <td colspan="3" style="text-align: center;">
               {{ measureStartTime }}-{{ measureEndTime }}
          
              </td>
              <td colspan="2" style="text-align: center;">加长杆XL[-3,0.5]</td>
           
              
              <td></td>
              <td  style="text-align: center;">R[0,0.1]</td>
              <td   style="text-align: center;"> 刀长度[-3,0.5] </td>
              <td  style="text-align: center;"> 对刀长度[0,3] </td>
              <td   style="text-align: center;">L[-3,0.5]</td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr class="success-row" >
              <td colspan="2" style="text-align: center;">
                <!-- 刀库异常编号<p v-html="faultNo">           
                </p>  -->
                <!-- <el-tooltip :content="faultNo=='True' ? '可写' : '不可写'" placement="top">
      <i :class="['status-icon', faultNo=='True' ? 'el-icon-add-location text-success' : 'el-icon-delete-location text-danger']"></i>
    </el-tooltip> -->
    <template v-if="description=='测量合格,请入库！'">
                  <el-tooltip :content="faultNo=='True' ? '可入库' : '不可入库'" placement="top">
                  <div style="color:green;size: 18px; font-weight: bold" class="input-icon el-icon-add-location"></div>
                </el-tooltip>
                {{ description }}
                </template>
                <template v-if="description!='测量合格,请入库！'">
                  <el-tooltip :content="faultNo=='True' ? '可入库' : '不可入库'" placement="top">
                  <div style="color:red;size: 18px; font-weight: bold" class="input-icon el-icon-delete-location"></div>
                </el-tooltip>
                {{ description }}
                </template>
                <!-- <template v-if="faultNo">
                  <span style='color:red'>刀库异常编号:{{ faultNo }}</span>
                </template> -->
              </td>

              <td style="text-align: center;">【{{this.togetherSeq}}】放刀中:{{ this.isKnifeOngoing }}放刀完成:{{ this.isKnifeCompleted }}</td>
              <td colspan="4" style="text-align: center;">
                <template v-if="measureResultStr.length>0">
                  <p style="color: red;" v-html="measureResultStr"></p>
                  </template>
                <template v-else>
                  <span style='color:green'>正常</span>
                </template>
              </td>
            
      
              <td colspan="3"  style="text-align: center;">
                <template v-if="faultNoMeasure!=='0'">
                  <p style="color: red;" v-html="faultNoMeasureStr"></p>
                  </template>
                <template v-else>
                  <span style='color:green'>正常</span>
                </template>
               
              </td>
         
              
           
              <td colspan="2"  style="text-align: center;">
               <template v-if="(isWriteRfid=='False'&&isUse=='True')">
                <button type="button" class="el-button el-button--primary" @click="PlcRestart('PlcRestart')">异常重新启动</button>
                  </template>
                <template v-else>
                  <span style='color:green'>--</span>
                </template>
                
               
              </td>
              <td colspan="2">
                <template v-if="(isInOut=='InOut'&&isUse=='True')">
                <button type="button" class="el-button el-button--primary" @click="AskInStock('PlcInStock')">判定入库</button>
                  </template>
                <template v-else>
                  <span style='color:green'>--</span>
                </template>
                <br>
                <br>
                <template v-if="(isInOut=='InOut'&&isUse=='True')">
                <button type="button" class="el-button el-button--primary" @click="AskOutStock('PlcOutStock')">退出整刀</button>
                  </template>
                <template v-else>
                  <span style='color:green'>--</span>
                </template>
              </td>
              
        
            </tr>
          </tbody>
        </table>
        <!-- <p v-html="mes">           
</p>  -->
      </el-tab-pane>
     
    </el-tabs>
  </div>
</template>
<script>
import VolTable from "@/components/basic/VolTable.vue";
import axios from 'axios';
export default {
  components: {
    VolTable
  },
  methods: {
    
    loadBefore (params, callback) {
      var _row;
      //获取主表选中的行
      this.$emit("parentCall", ($vue) => {
        debugger;
        var rows = $vue.getSelectRows();
        if (rows.length) {
          _row = rows[0];
        }
      });
      if (!_row) {
        //取消选中，清空明细
        return (this.$refs.tableList.rowData.length = 0);
        //  return this.$Message.error("请选中主表行数据");
      }
      params.wheres =[{ name: "Process_Id", value: _row.Process_Id}];
      return callback(true);
    },
    /*
    //异常重新启动
    async PlcRestart(action,row)
    {
    
      let url = `A_UpperComputer/${action}`;
      let tigger = false;
      this.$confirm(
        "确认要重新启动吗？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        }
      ).then(() => {
        if (tigger) return;
        tigger = true;
        const response1 = await axios.post(url, null, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
     

      });

     
      

    },
    */
   //出库
   async AskOutStock(action, row) {
    debugger;
    row={Id:this.vendor_code,Identifier:''};
  // 防重复提交检查
  if (this.isRestarting) {
    this.$message.warning('已有退出整刀，请稍候')
    return
  }

  try {
    // 显示带加载状态的确认对话框
    const confirm = await this.$confirm(
      "确认要执行退出整刀吗？该操作不可逆转！",
      "退出整刀确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
        lock: true, // 锁定背景
        closeOnClickModal: false, // 禁用点击遮罩关闭
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true // 按钮显示加载状态
            instance.confirmButtonText = '正在提交...'
          }
          done()
        }
      }
    )

    // 开始执行操作
    this.isRestarting = true
   // const url = `/api/A_UpperComputer/${encodeURIComponent(action)}`
   let url = `A_UpperComputer/${encodeURIComponent(action)}`;
    // 带超时设置的请求
    const response = await axios.post(url, row, {
      headers: {
       'Content-Type': 'application/json'
       // 'X-Requested-With': 'XMLHttpRequest'
      },
      timeout: 30000 // 30秒超时
    })
    // 处理响应
    if (response.data.status) {
      this.$message.success('退出整刀指令已成功发送')
      // 可选：更新相关状态或数据
      if (row) this.$set(row, 'status', 'restarting')
    } else {
      this.$message.error(`重启失败：${response.data.message}`)
    }
  } catch (error) {
    // 错误处理
    if (error.includes('cancel')) {
      console.log('用户取消操作')
    } else if (error.code === 'ECONNABORTED') {
      this.$message.error('请求超时，请检查设备连接')
    } else {
      console.error('重启错误:', error)
      this.$message.error(`操作失败：${error.message || '未知错误'}`)
    }
  } finally {
    this.isRestarting = false
  }
},
   //入库
    async AskInStock(action, row) {
      debugger;
      row={Id:this.vendor_code,Identifier:''};
  // 防重复提交检查
  if (this.isRestarting) {
    this.$message.warning('已有正在进行入库，请稍候')
    return
  }

  try {
    // 显示带加载状态的确认对话框
    const confirm = await this.$confirm(
      "确认要执行入库吗？该操作不可逆转！",
      "入库确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
        lock: true, // 锁定背景
        closeOnClickModal: false, // 禁用点击遮罩关闭
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true // 按钮显示加载状态
            instance.confirmButtonText = '正在提交...'
          }
          done()
        }
      }
    )

    // 开始执行操作
    this.isRestarting = true
   // const url = `/api/A_UpperComputer/${encodeURIComponent(action)}`
   let url = `A_UpperComputer/${encodeURIComponent(action)}`;
    // 带超时设置的请求
    const response = await axios.post(url, row, {
      headers: {
       'Content-Type': 'application/json'
       // 'X-Requested-With': 'XMLHttpRequest'
      },
      timeout: 30000 // 30秒超时
    })
    // 处理响应
    if (response.data.status) {
      this.$message.success('入库指令已成功发送')
      // 可选：更新相关状态或数据
      if (row) this.$set(row, 'status', 'restarting')
    } else {
      this.$message.error(`重启失败：${response.data.message}`)
    }
  } catch (error) {
    // 错误处理
    if (error.includes('cancel')) {
      console.log('用户取消操作')
    } else if (error.code === 'ECONNABORTED') {
      this.$message.error('请求超时，请检查设备连接')
    } else {
      console.error('重启错误:', error)
      this.$message.error(`操作失败：${error.message || '未知错误'}`)
    }
  } finally {
    this.isRestarting = false
  }
},
    async PlcRestart(action, row) {
  // 防重复提交检查
  if (this.isRestarting) {
    this.$message.warning('已有正在进行异常重新启动，请稍候')
    return
  }

  try {
    // 显示带加载状态的确认对话框
    const confirm = await this.$confirm(
      "确认要执行异常重新启动吗？该操作不可逆转！",
      "重新启动确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
        lock: true, // 锁定背景
        closeOnClickModal: false, // 禁用点击遮罩关闭
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true // 按钮显示加载状态
            instance.confirmButtonText = '正在提交...'
          }
          done()
        }
      }
    )

    // 开始执行操作
    this.isRestarting = true
   // const url = `/api/A_UpperComputer/${encodeURIComponent(action)}`
   let url = `A_UpperComputer/${encodeURIComponent(action)}`;
    // 带超时设置的请求
    const response = await axios.post(url, null, {
      headers: {
       'Content-Type': 'application/json'
       // 'X-Requested-With': 'XMLHttpRequest'
      },
      timeout: 30000 // 30秒超时
    })
    // 处理响应
    if (response.data.status) {
      this.$message.success('异常重新启动指令已成功发送')
      // 可选：更新相关状态或数据
      if (row) this.$set(row, 'status', 'restarting')
    } else {
      this.$message.error(`重启失败：${response.data.message}`)
    }
  } catch (error) {
    // 错误处理
    if (error.includes('cancel')) {
      console.log('用户取消操作')
    } else if (error.code === 'ECONNABORTED') {
      this.$message.error('请求超时，请检查设备连接')
    } else {
      console.error('重启错误:', error)
      this.$message.error(`操作失败：${error.message || '未知错误'}`)
    }
  } finally {
    this.isRestarting = false
  }
},
    async PlcVeiwPlan(action){
      let url = `A_UpperComputer/${action}`;
      const getFaultType = (status,sys_DictionaryLists) => {
  const statusMap = {
    // '1': '刀具模版给了，刀长没给',
    // '2': '刀柄模版给了，刀柄长没给',
    // '3': '加长杆1模版给了，加长杆1长没给',
    // '4':'刀具模版没给',
    // '5':'刀柄模版没给',
    // '0':'-'
  } 

  for (let index = 0; index < sys_DictionaryLists.length; index++) {
    const element = sys_DictionaryLists[index];
    if (element.dicValue !== "") {
      Object.assign(statusMap, { [element.dicValue]: element.dicName });
    }
   
    
  }
 
 
  console.log(statusMap);
  return statusMap[status] || '未知异常';
}

      const response1 = await axios.post(url, null, {
          headers: {
            'Content-Type': 'application/json'
          }
        });

      //  const response =await this.http.post(url, null, true).then((result) => {
      
      //     if(result.status==false){
      //       this.$message.error(result.message);
      //     }else{
                     
      
      //       if(result.data.isFalut=="True"){
      //         this.mes+="刀库异常编号:"+result.data.faultNo+"<br>"}
      //       this.mes+="放刀完成:"+result.data.isKnifeCompleted+"<br>"
      //       this.mes+="放刀中:"+result.data.isKnifeOngoing+"<br>"
      //       this.mes+="放刀位置编号:"+result.data.knifeLocationNumber+"<br>"
    
      //      //this.$message.success('执行成功');
      //     // this.search();
      //     // this.tableDataOld.push({isUse:result.data.isUse,
      //     //   isWriteRfid:result.data.isWriteRfid,isFalut:result.data.isFalut,location:result.data.location, date: '2023-10-01', holder_Code:result.data.holder_Code,
      //     // r:result.data.r,tool_name:result.data.tool_name,identifier:result.data.identifier, processing_machines: '北京市朝阳区' });
      //     }
        
      //    });
      //    debugger;
         var result=response1.data;
         console.log(result);
      
 //通过  this.$emit('parentCall')获取生成页面$parent对象，

         this.tableData=[];
         this.mes="";   
         this.tableData.push({handle_type:result.data.handle_type,rfidCode:result.data.rfidCode,holderTypeId:result.data.holderTypeId,isUse:result.data.isUse,
            isWriteRfid:result.data.isWriteRfid,isFalut:result.data.isFalut,location:result.data.location, date: '2023-10-01', holder_Code:result.data.holder_Code,
          r:result.data.r,tool_name:result.data.tool_name,identifier:result.data.identifier, processing_machines: '' });
          this.faultNoMeasure=result.data.faultNoMeasure;
          this.isWriteRfid=result.data.isWriteRfid;
          this.isUse=result.data.isUse;
          this.knife_width=result.data.knife_width;
          this.reality_knife_width=result.data.reality_knife_width;
          this.knife_length=result.data.knife_length;
          this.reality_knife_length=result.data.reality_knife_length;
          this.description=result.data.description;
          this.measureStartTime=result.data.measureStartTime;
          this.measureEndTime=result.data.measureEndTime;
          this.holderLTheory=result.data.holderLTheory;
          this.holderL=result.data.holderL;
          this.ace1LTheory=result.data.ace1LTheory;
          this.ace1L=result.data.ace1L;
          this.vendor_code=result.data.vendor_code;
          this.isInOut=result.data.isInOut;
          this.togetherSeq=result.data.togetherSeq;
          if(this.faultNoMeasure!=="0"){
            this.faultNoMeasureStr='异常'+this.faultNoMeasure+':'+getFaultType(this.faultNoMeasure,result.data.sys_DictionaryLists); 
          }
          this.measureResultStr="测量结果:"+"理论刀径"+this.knife_width+"实际"+this.reality_knife_width;
          this.measureResultStr+="理论刀长"+this.knife_length+"实际"+this.reality_knife_length+"<br>";
          this.measureResultStr+="理论刀柄刀长"+this.holderLTheory+"实际"+this.holderL+"<br>";
          this.measureResultStr+="理论加长杆1长理论"+this.ace1LTheory+"实际"+this.ace1L+"<br>";
          //this.measureResultStr+="理论刀柄刀长"+this.holderLTheory+"实际"+this.holderL+"<br>";
          // Ace1LTheory,Ace1L,
          // HolderBD,HolderBDTheory
          
          if(result.data.isFalut=="True"){
            this.faultNo=result.data.faultNo;
              this.mes+="刀库异常编号:"+result.data.faultNo+"<br>"}
              this.isKnifeCompleted=result.data.isKnifeCompleted;
            this.mes+="放刀完成:"+result.data.isKnifeCompleted+"<br>"
            this.isKnifeComplisKnifeOngoingeted=result.data.isKnifeOngoing;
            this.mes+="放刀中:"+result.data.isKnifeOngoing+"<br>"

           // this.mes+="放刀位置编号:"+result.data.knifeLocationNumber+"<br>"
    }
  },
  data () {
    return {
      isRestarting: false, // 重启状态锁
      tableDataOld: [],
      tableData: [],
      isUse:'False',
      isWriteRfid:'False',
      mes: '',
      faultNo:'',
      faultNoMeasureStr:'-',
      measureResultStr:'-',
      isKnifeCompleted:'',
      isKnifeOngoing:'',
      faultNoMeasure:'0',
      description:'-',
      vendor_code:'-',
      measureStartTime: '-',
      measureEndTime: '-',
      isLoading: true // 初始加载状态为true
      //从生成的代码sellorder2.vue里面把明细配置复制过来就能用
    
    }
  }
}
</script>
<style scoped>
 h3{
     font-weight: 500;
    padding-left: 10px;
    background: white;
    margin-top: 8px;
    padding-bottom: 5px;
 }
 .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  /* 新增样式部分 */
.optimized-table {
  width: 100%;
  border-collapse: collapse;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  table-layout: fixed; /* 固定列宽 */
}

.optimized-table th {
  background: #409EFF;
  color: white;
  padding: 12px 8px;
  font-size: 14px;
  border: 1px solid #ddd;
}

.optimized-table td {
  padding: 10px 8px;
  border: 1px solid #eee;
  font-size: 13px;
  word-break: break-word;
}

.status-icon {
  font-size: 18px;
  vertical-align: middle;
}

.state-indicator {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.ready-state {
  background: #e6f4ff;
  color: #409EFF;
}

.warning-state {
  background: #fff7e6;
  color: #ff9900;
}

/* 斑马纹效果 */
tbody tr:nth-child(odd) {
  background: #fafafa;
}

/* 响应式处理 */
@media screen and (max-width: 1600px) {
  .optimized-table {
    font-size: 12px;
  }
}

/* 悬停效果 */
tbody tr:hover {
  background-color: #f5f7fa !important;
  transition: background 0.3s;
}

/* 对齐优化 */
.align-center {
  text-align: center !important;
}
.align-right {
  text-align: right !important;
}
</style>